<?php
namespace app\shop\service\company;
use app\shop\model\company\ExamineLog;
use app\shop\model\company\ExamineTpl;
use app\shop\model\company\Examine as ExamineModel;
use app\common\service\Result;
use app\shop\model\company\WorkReport;
use app\shop\model\user\User;
use app\shop\model\company\Staff;
class Examine
{
    public function list($data)
    {
        $app_id = request()->app_id;
        $map = [
            ['app_id', '=', $app_id]
        ];
        if (isset($data['department_id']) && $data['department_id']) {
            $map[] = ['department_id', 'in', $data['department_id']];
        }
        $page_size = $data['page_size'] ?? 20;
        $lists = ExamineTpl::where($map)->with(['department'])->order('sort desc,id desc')
            ->paginate($page_size);
        return Result::success($lists);
    }


    public function add($data)
    {
        $data['app_id'] = request()->app_id;
        ExamineTpl::create($data);
        return Result::success();
    }

    public function edit($data)
    {
        $info = ExamineTpl::find($data['id']);
        if (!$info) {
            return Result::error('数据不存在');
        }
        $info->save($data);
        return Result::success();
    }

    public function delete($id)
    {
        $info = ExamineTpl::find($id);
        if (!$info) {
            return Result::error('数据不存在');
        }
        $info->delete();
        return Result::success();
    }

    public function info($id)
    {
        $info = ExamineTpl::field('id,title,department_id,content,sort')->find($id);
        return Result::success($info);
    }

    public function detail($id)
    {
        $info = ExamineTpl::with([
            'department' => function ($query) {
                $query->field('id,title');
            },
        ])->find($id);
        return Result::success($info);
    }

    public function reports($data)
    {
        try {
            $app_id = request()->app_id;
            $map = [
                ['app_id', '=', $app_id]
            ];
            if (isset($data['user_id']) && $data['user_id']) {
                $map[] = ['user_id', '=', $data['user_id']];
            }
            if (isset($data['department_id']) && $data['department_id']) {
                $map[] = ['department_id', 'in', $data['department_id']];
            }
            if (isset($data['create_time']) && $data['create_time']) {
                $map[] = ['create_time', 'between', [$data['create_time'][0], $data['create_time'][1]]];
            }
            $username = $data['username'] ?? '';
            if($username){
                $ids = User::where('real_name', 'like', "%$username%")->where('app_id',$app_id)->column('user_id');
                $map[] = ['user_id', 'in', $ids];
            }
            $page_size = $data['page_size'] ?? 20;
            $lists = WorkReport::with(['user','department'])->where($map)->paginate($page_size);
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function reportInfo($id)
    {
        $info = WorkReport::with(['user', 'department'])->find($id);
        return Result::success($info);
    }

    public function staffList($data)
    {
        $app_id = request()->app_id;
        $page_size = $data['page_size'] ?? 20;
        $map = [
            ['Examine.app_id', '=', $app_id]
        ];
        if (isset($data['department_id']) && $data['department_id']) {
            $map[] = ['Examine.department_id', 'in', $data['department_id']];
        }
        if (isset($data['user_id']) && $data['user_id']) {
            $map[] = ['Examine.user_id', 'in', $data['user_id']];
        }
        if (isset($data['title']) && $data['title']) {
            $map[] = ['Examine.title', 'like', "%" . $data['title'] . "%"];
        }
        $username = $data['username'] ?? '';
        $lists = ExamineModel::withJoin([
            'user' => function ($query) use ($username) {
                $query->whereLike('real_name', "%$username%");
            }
        ])->where($map)->with(['user', 'department', 'managerUser'])->append(['status_text'])->paginate($page_size);
        return Result::success($lists);
    }

    public function staffInfo($id)
    {
        try {
            $info = ExamineModel::with(['managerUser'])->append(['status_text'])->find($id);
            return Result::success($info);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function staffAdd($data)
    {
        try {
            $app_id = request()->app_id;
            $user_id = $data['user_id'];
            $staff = Staff::find($user_id);
            if (!$staff) {
                return Result::error('员工不存在');
            }
            $examine = ExamineModel::create([
                'app_id' => $app_id,
                'user_id' => $user_id,
                'department_id' => $staff['department_id'],
                'title' => $data['title'],
                'content' => $data['content'],
                'status' => 0,
                'start_time' => $data['examine_date'][0] ?? time(),
                'end_time' => $data['examine_date'][1] ?? 0,
            ]);
            return Result::success($examine);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function staffSave($data)
    {
        try {
            $id = $data['id'] ?? 0;
            $user_id = $data['add_user'] ?? 0;
            $info = ExamineModel::find($id);
            if (!$info) {
                return Result::error('数据不存在');
            }
            $sign_img = $data['sign_img'] ?? "";
            $sign_type = $data['sign_type'] ?? "staff";
            if($sign_img){
                if ($sign_type == "staff") {
                    if ($info->user_id != $user_id) {
                        return Result::error('没有操作权限');
                    }
                    $data['sign'] = $sign_img;
                }
                elseif($sign_type=="hr"){
                    $staff = Staff::with('department')->find($user_id);
                    if (!$staff || $staff['department']['is_hr'] != 1) {
                        return Result::error('没有操作权限');
                    }
                    $data['hr'] = $user_id;
                    $data['hr_sign'] = $sign_img;
                }
            }
            $info->save($data);
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function staffLogs($data){
        $page_size = $data['page_size'] ?? 20;
        $examine_id = $data['examine_id'] ?? 0;
        if(!$examine_id){
            return Result::error('参数错误');
        }
        $map = [
            ['examine_id', '=', $examine_id],
        ];
        $lists = ExamineLog::where($map)->with(['managerUser'])->order('id desc')->paginate($page_size);
        return Result::success($lists);
    }

    public function is_manager($examine_id){
        $user_id = request()->user_id;
        if(!$user_id){
            return Result::success(['is_manager'=>false]);
        }
        $user_staff = Staff::find($user_id);
        $info = ExamineModel::find($examine_id);
        //员工的部门
        $staff = Staff::with(['department'])->find($info->user_id);
        if($user_staff['department_id']==$staff['department_id'] && $user_staff['type']>=$staff['type']){
            return Result::success(['is_manager'=>true]);
        }else{
            return Result::success(['is_manager'=>false]);
        }
    }

    public function addLog($data)
    {
        try {
            $examine_id = $data['examine_id'];
            $info = ExamineModel::find($examine_id);
            if (!$info || $info->status!=0) {
                return Result::error('考核不存在或已结束');
            }
            if($info->user_id!=request()->user_id){
                return Result::error('没有操作权限');
            }
            $log = ExamineLog::create([
                'examine_id' => $examine_id,
                'progress' => $data['progress']
            ]);
            return Result::success($log);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function saveLog($data)
    {
        try {
            $info = ExamineLog::find($data['id']);
            if (!$info) {
                return Result::error('记录不存在');
            }
            $examine = ExamineModel::find($info->examine_id);
            if($examine->user_id==$data['manager']){
                return Result::error('不能给自己打分');
            }
            $staff = Staff::find($examine->user_id);
            $manager = Staff::find($data['manager']);
            if(!$staff || !$manager){
                return Result::error('员工不存在');
            }
            if($manager['department_id']!=$staff['department_id'] || $manager['type']<$staff['type']){
                return Result::error('没有操作权限');
            }
            $info->save($data);
            //对应的考核进度修改
            $examine->save(['progress'=>$info['progress']]);
            return Result::success($data);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function addReport($data)
    {
        try {
            $app_id = request()->app_id;
            $user_id = $data['user_id'];
            $staff = Staff::find($user_id);
            if (!$staff) {
                return Result::error('员工不存在');
            }
            if($staff->type<2){
                return Result::error('没有操作权限');
            }
            $report = WorkReport::create([
                'app_id' => $app_id,
                'user_id' => $user_id,
                'department_id' => $staff['department_id'],
                'title' => $data['title'],
                'content' => $data['content'],
                'file'=>$data['file'],
            ]);
            return Result::success($report);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
}